package com.cngphone.AnFetion.Fetion.SIPC;

import java.util.ArrayList;

import org.w3c.dom.DOMException;

import com.cngphone.AnFetion.FetionSIPC;
import com.cngphone.AnFetion.FetionUri;
import com.cngphone.AnFetion.Fetion.TcpSendAndReceive;
import com.cngphone.AnFetion.tools.StrUtil;

public class IMDelete extends SIPCBase {
    private FetionUri fetionid;
    private FetionUri uri;
    private boolean ban;

    private FetionSIPC acceptsipc;

    public IMDelete(SerialManager serialManager, TcpSendAndReceive connection, FetionUri fetionid,
            FetionUri uri, boolean ban) {
        super(serialManager, connection);
        this.fetionid = fetionid;
        this.uri = uri;
        this.ban = ban;
    }

    @Override
    public boolean execute() {
        ArrayList<FetionSIPC.HeaderPair> headers = new ArrayList<FetionSIPC.HeaderPair>();
        headers.add(new FetionSIPC.HeaderPair("F", this.fetionid.getId()));
        headers.add(new FetionSIPC.HeaderPair("I", serialManager.getISerial() + " "));
        headers.add(new FetionSIPC.HeaderPair("Q", serialManager.getQSerial() + " S"));
        headers.add(new FetionSIPC.HeaderPair("N", "DeleteBuddy"));
        // headers.add(new FetionSIPC.HeaderPair("K", "text/plain"));

        StringBuilder body = new StringBuilder();
        body.append("<args><contacts><buddies><buddy uri=\"").append(uri.toString()).append("\"");
        if (ban) {  // TODO ban is not finished 
            body.append(" result=\"1\" buddy-lists=\"\" expose-mobile-no=\"1\" expose-name=\"1\"");
        } else {
            // body.append("");
        }
        body.append(" /></buddies></contacts></args>");
        headers.add(new FetionSIPC.HeaderPair("L", StrUtil.getLength(body)));

        acceptsipc = new FetionSIPC(SIPC_COMMON_HEADER, headers, body.toString());
        if (this.SendAndReceiveResponse(acceptsipc)) {
            try {
                if (acceptsipc.response.getResponseCmdLine().code.equals(SIPC_RESPONSE_CODE_OK)) {
                    return true;
                }
            } catch (NumberFormatException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (DOMException e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                this.onSetText(e.getMessage());
                e.printStackTrace();
            }
        }
        return false;
    }

}
